package cz.matasek.dbLogger.gui;

import cz.matasek.dbLogger.Constant;
import cz.matasek.dbLogger.exception.DbLoggerRuntimeException;
import cz.matasek.dbLogger.model.DateTime;
import java.sql.ResultSet;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * This class is a <code>TableModel</code> of the historical content of a table.
 *
 * @author Luboš Matásek
 */
public class HistoricalQueryResult extends ResultSetTableModel {

    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 1667364041745959769L;
    /**
     * Name of the table.
     */
    private String tableName;
    /**
     * Date and time of the historical view.
     */
    private DateTime dateTime;

    /**
     * Creates a new <code>HistoricalQueryResult</code> table model.
     *
     * @param queryResultSet the result set of a query
     * @param tableName the name of the table
     * @param dateTime the date and time of the historical view
     */
    public HistoricalQueryResult(ResultSet queryResultSet,
            String tableName, DateTime dateTime) {
        super(queryResultSet);

        this.tableName = tableName;
        this.dateTime = dateTime;
    }

    /**
     * Returns XML document containing historical table content.
     * 
     * @return XML document containing historical table content
     */
    @Override
    public Document getXML() {
        try {
            Document xml =
                    DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().newDocument();
            xml.setXmlStandalone(true);

            Element table = xml.createElementNS(
                    Constant.DB_LOGGER_NAMESPACE, "table");
            table.setAttribute(
                    "xmlns:xsi", Constant.XML_SCHEMA_NAMESPACE);
            table.setAttribute("name", tableName);
            table.setAttribute("dateTime", dateTime.toString().replace(" ", "T"));

            for (Object[] rowData : data) {
                Element row = xml.createElement("row");

                for (int i = 1; i < rowData.length; ++i) {
                    Element col = xml.createElement("col");
                    col.setAttribute("name",
                            columnTitles[i].substring(0, columnTitles[i].indexOf(" ")).toLowerCase());
                    if (rowData[i] == null) {
                        col.setAttribute("xsi:nil", "true");
                    } else {
                        col.setTextContent(rowData[i].toString());
                    }
                    row.appendChild(col);
                }

                table.appendChild(row);
            }

            xml.appendChild(table);

            return xml;
        } catch (ParserConfigurationException ex) {
            throw new DbLoggerRuntimeException(ex.getMessage());
        }
    }
}
